<?php

class Controller_Admin_Site extends Controller
{
    public function __construct()
    {
        $aUser = getCurrentUser();
		if (!isset($aUser['utype']) || $aUser['utype'] != 'admin')
		{
		    Controller_Error::forbidden();
		}
    }
    
	public function index()
	{
	    if (isset($this->params[0]))
	    {
	        switch ($this->params[0])
	        {
	            case 'delete':
	                $id = isset($this->params[1]) ? intval($this->params[1]) : 0;
	                $site = new Model_Site($id);
	                $site->delete();
	                DB::query('UPDATE places SET site_id = 0 WHERE site_id = '.$id);
	                Redirect('/admin/site');
	            break;
	        }
	    }
	    $site = new Model_Site();
	    $aSites = $site->find();
		$this->view->add(array(
		    'aSites' => $aSites,
		));
		return $this->view->render('admin/site/list.tpl');
	}
	
	public function edit()
	{
	    $id = isset($this->params[0]) ? intval($this->params[0]) : 0;
	    $site = new Model_Site($id);
        $aData = $site->values;

        switch (Request::getStr('act'))
        {
            case 'delplace':
                $iPlaceId = Request::getInt('id');
                $place = new Model_Place($iPlaceId);
                $place->delete();
                Redirect('/admin/site/edit/'.$id);
            break;
        }

	    $errors = array();
	    if (Request::isPost())
	    {
	        $aData = Request::getPost();
    		$validator = new Validator();
    		$validator->add(new Rule_NotEmpty('title', 'Введите название'));
    		$validator->add(new Rule_NotEmpty('url', 'Введите URL'));
    		if ($validator->validate($aData))
    		{
		        if ($id)
		        {
		            $site->save($aData);
		        }
		        else
		        {
		            $site->values = $aData;
    		        $site->save();
		        }
		        Redirect('/admin/site');
    		}
    		else
    		{
    		    $errors = $validator->errors;
    		}
	    }
	    
	    if ($id)
	    {
	        $aPlaces = DB::getRows('SELECT * FROM places WHERE site_id = '.$id);
	        $this->view->add('aPlaces', $aPlaces);
	    }
	    
		$this->view->add(array(
		    'id'         => $id,
		    'aData'      => $aData,
		    'errors'     => $errors,
		));
		return $this->view->render('admin/site/edit.tpl');
	}
	

}